package DSN;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class GetDivStatusFromMpay {
    private static final int TARGET_HOUR = 2; // 凌晨2点
    public void asyncDivData() throws Exception {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
      /*  // 单次任务
        executor.schedule(() -> {
            System.out.println("单次任务@" + System.currentTimeMillis());
        }, 1, TimeUnit.SECONDS);

        // 固定速率周期任务
        executor.scheduleAtFixedRate(() -> {
            System.out.println("固定速率任务");
        }, 2, 3, TimeUnit.SECONDS);*/
        // 固定延迟周期任务
        executor.scheduleWithFixedDelay(() -> {
        try{
            JdbcTemplate jdbcTemplateDivData = new JdbcTemplate(new DBUtil().Hikar_DataSource_JTJT());
            JdbcTemplate jdbcTemplateMpay = new JdbcTemplate(new DBUtil().Hikar_DataSource_MPAY());
            final boolean[] isContinue = {true};
            String div_passid_nodiv="update DIV_PASSID_ALL_NODIV set ISASYNC=1 where PASSID=:PASSID" ;
            String div_passid_all_jt1Check="merge into DIV_PASSID_ALL_JT1_RESULT t1 " +
                    "using(select :passid as passid,:status as status,:PROVICNECODE as PROVICNECODE," +
                    ":PROVICNENAME as PROVICNENAME,:SUBCOMNO as SUBCOMNO,:SUBCOMNAME as SUBCOMNAME," +
                    "to_date(:STATUSTIME,'yyyy-mm-dd HH24:mi:ss') as STATUSTIME, " +
                    "to_date(:CLASSDATE,'yyyy-mm-dd HH24:mi:ss') as CLASSDATE " +
                    " from dual) t2 on(t1.passid=t2.passid ) when matched then update set t1.status=t2.status," +
                    "t1.PROVICNECODE=t2.PROVICNECODE,t1.PROVICNENAME=t2.PROVICNENAME,t1.SUBCOMNO=t2.SUBCOMNO," +
                    "t1.SUBCOMNAME=t2.SUBCOMNAME,t1.STATUSTIME=t2.STATUSTIME,t1.CLASSDATE =t2.CLASSDATE " +
                    " when not matched then insert( PASSID,STATUS,PROVICNECODE,PROVICNENAME,SUBCOMNO,SUBCOMNAME,STATUSTIME,CLASSDATE) " +
                    "values (t2.passid,t2.status,t2.PROVICNECODE, t2.PROVICNENAME, t2.SUBCOMNO, t2.SUBCOMNAME, t2.STATUSTIME,t2.CLASSDATE)";


            String sqlQuery="select PASSID,STATUS,PROVICNECODE,PROVICNENAME,SUBCOMNO,SUBCOMNAME,STATUSTIME,CLASSDATE " +
                    "from DIV_PASSID_ALL_NODIV where ISASYNC is null and STATUS is not null ";
            List<Map<String, Object>> gpa_list = jdbcTemplateMpay.queryForList(sqlQuery);
            ArrayList<Object[]> div_passid_jt1_params = new ArrayList<>();
            ArrayList<Object[]> div_passid_nodiv_params = new ArrayList<>();
            if(!gpa_list.isEmpty()){
                gpa_list.forEach(gpa-> {
                    String passid = gpa.get("PASSID").toString();
                    String status = gpa.get("STATUS").toString();
                    String provicneCode = gpa.get("PROVICNECODE") !=null ?gpa.get("PROVICNECODE").toString():"";
                    String provicneName = gpa.get("PROVICNENAME") !=null ?gpa.get("PROVICNENAME").toString():"";
                    String subcomno = gpa.get("SUBCOMNO") !=null ?gpa.get("SUBCOMNO").toString():"";
                    String subcomname = gpa.get("SUBCOMNAME") !=null ?gpa.get("SUBCOMNAME").toString():"";
                    String statustime = gpa.get("STATUSTIME") !=null ?gpa.get("STATUSTIME").toString().substring(0,19):"";
                    String classdate = gpa.get("CLASSDATE") !=null ?gpa.get("CLASSDATE").toString().substring(0,19):"";
                    div_passid_jt1_params.add(new Object[]{passid,status,provicneCode,provicneName,
                            subcomno,subcomname,statustime,classdate});
                    div_passid_nodiv_params.add(new Object[]{passid});
                });
            };

            DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(Objects.requireNonNull(jdbcTemplateDivData.getDataSource()));
            TransactionTemplate transactionTemplate = new TransactionTemplate(dataSourceTransactionManager);
            transactionTemplate.execute(new TransactionCallback<Object>() {
                @Override
                public Object doInTransaction(TransactionStatus transactionStatus) {
                    try {
                        LogClass.info("MPAY--->NMGJTJT,未拆分数据开始发送" + LocalTime.now());
                        jdbcTemplateDivData.batchUpdate(div_passid_all_jt1Check, div_passid_jt1_params);
                        LogClass.info("MPAY--->NMGJTJT,未拆分数据发送结束" + LocalTime.now());

                    } catch (Exception e) {
                        LogClass.error("MPAY--->NMGJTJT,未拆分数据事务执行错误，错误信息" + e.getMessage());
                        transactionStatus.setRollbackOnly();
                        isContinue[0] =false;
                    }
                    return null;

                }
            });
            if(isContinue[0]){
                DataSourceTransactionManager dataSourceTransactionManagerMpay = new DataSourceTransactionManager(Objects.requireNonNull(jdbcTemplateMpay.getDataSource()));
                TransactionTemplate transactionTemplateMpay = new TransactionTemplate(dataSourceTransactionManagerMpay);
                transactionTemplateMpay.execute(new TransactionCallback<Object>() {
                    @Override
                    public Object doInTransaction(TransactionStatus transactionStatus) {
                        try {
                            LogClass.info("MPAY,未拆分数据修改同步字段开始发送" + LocalTime.now());
                            jdbcTemplateMpay.batchUpdate(div_passid_nodiv, div_passid_nodiv_params);
                            LogClass.info("MPAY,未拆分数据修改同步字段发送结束" + LocalTime.now());

                        } catch (Exception e) {
                            LogClass.error("MPAY,未拆分数据修改同步字段事务执行错误，错误信息" + e.getMessage());
                            transactionStatus.setRollbackOnly();
                        }
                        return null;

                    }
                });
            }


        }catch (Exception e){
            LogClass.exception(e);
        }

        }, calculateInitialDelay(), 24 * 60 * 60 * 1000, TimeUnit.MILLISECONDS);// 24小时周期（会被动态调整覆盖）

    }
    private static long calculateInitialDelay() {
        LocalTime now = LocalTime.now();
        LocalTime targetTime = LocalTime.of(TARGET_HOUR, 0);

        long delay = now.until(targetTime, ChronoUnit.MILLIS);
        if (delay < 0) {
            delay += TimeUnit.DAYS.toMillis(1); // 如果今天已过目标时间，延迟到明天
        }
        return delay;
    }
}
